import React, { useState } from "react";
import { definePageConfig, useAuth,history } from "ice";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { ProFormCheckbox, ProFormText, LoginForm } from "@ant-design/pro-form";
import styles from "./index.module.css";
import type { LoginParams, LoginResult } from "@/interfaces/user";
import logo from "@/assets/logo.png";
import { handleRes } from "@/utils/request";
import { loginApi } from "./api";

const Login: React.FC = () => {
  const handleSubmit = async (values: LoginParams) => {
    // const response = await request.post("/auth/login", values);
    const res = await handleRes({
      api: loginApi.login,
      data: values,
      success: {
        msg: true,
      },
    });

    const { token, userInfo } = res;

    // 存储token和用户信息到localStorage
    localStorage.setItem("token", token);
    localStorage.setItem("userInfo", JSON.stringify(userInfo));

    // 使用 window.location 进行跳转
    // window.location.href = "/";
    history?.push("/");
  };

  return (
    <div className={styles.container}>
      <LoginForm
        title="回收猫"
        logo={<img alt="logo" src={logo} />}
        subTitle="专业的化妆品和数码回收平台"
        onFinish={async (values) => {
          await handleSubmit(values as LoginParams);
        }}
      >
        <ProFormText
          name="userName"
          fieldProps={{
            size: "large",
            prefix: <UserOutlined className={"prefixIcon"} />,
          }}
          placeholder={"用户名或手机号"}
          rules={[
            {
              required: true,
              message: "请输入账户!",
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{
            size: "large",
            prefix: <LockOutlined className={"prefixIcon"} />,
          }}
          placeholder={"密码"}
          rules={[
            {
              required: true,
              message: "请输入密码！",
            },
          ]}
        />
        <div
          style={{
            marginBottom: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a
            style={{
              float: "right",
            }}
          >
            忘记密码
          </a>
        </div>
      </LoginForm>
    </div>
  );
};

export const pageConfig = definePageConfig(() => {
  return {
    title: "登录",
  };
});

export default Login;
